// OrderTimeoutConsumer.java
package edu.del.springbootredisbusinesspractice.consumer;

import edu.del.springbootredisbusinesspractice.commons.config.RabbitMQConfig;
import edu.del.springbootredisbusinesspractice.mapper.OrdersMapper;
import edu.del.springbootredisbusinesspractice.pojo.Orders;
import edu.del.springbootredisbusinesspractice.service.ProductStockService;
import edu.del.springbootredisbusinesspractice.service.repository.ProductStockRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Service;

import com.rabbitmq.client.Channel;

import java.io.IOException;
import java.util.Date;

@Slf4j
@Service
public class OrderTimeoutConsumer {

    @Autowired
    private OrdersMapper ordersMapper;

    @Autowired
    private ProductStockService productStockService;


    @RabbitListener(
            queues = RabbitMQConfig.DEAD_LETTER_QUEUE,
            containerFactory = "jsonRabbitListenerContainerFactory"
    )
    public void handleTimeoutOrder(
            @Payload Orders order,
            Channel channel,
            @Header(AmqpHeaders.DELIVERY_TAG) long deliveryTag) {

        try {
            log.info("【支付超时消费】检查订单是否超时未支付，orderNo: {}", order.getOrderNo());

            Orders currentOrder = ordersMapper.selectByOrderNo(order.getOrderNo());
            if (currentOrder == null) {
                log.warn("【支付超时消费】订单不存在，orderNo: {}", order.getOrderNo());
                channel.basicAck(deliveryTag, false);
                return;
            }

            if (currentOrder.getStatus() == 1) { // 未支付
                currentOrder.setStatus(5); // 已取消
                currentOrder.setUpdatedAt(new Date());
                ordersMapper.updateById(currentOrder);

                // 更新订单
                int updateResult = ordersMapper.updateById(currentOrder);

                if (updateResult > 0) {
                    String stockKey = "product:" + order.getProductId() + ":stock";
                    int count = order.getQuantity() != null ? order.getQuantity() : 1;
                    // 恢复库存
                    productStockService.incrementStockAndUpdateLocalCache(order.getProductId().intValue(), count);
                    log.info("【支付超时消费】订单已自动取消，orderNo: {}", order.getOrderNo());
                }

            } else {
                log.info("【支付超时消费】订单已支付，无需处理，orderNo: {}, status: {}", order.getOrderNo(), currentOrder.getStatus());
            }

            channel.basicAck(deliveryTag, false);

        } catch (Exception e) {
            log.error("【支付超时消费】处理异常，orderNo: {}", order.getOrderNo(), e);
            try {
                channel.basicNack(deliveryTag, false, false);
            } catch (IOException ex) {
                log.error("【支付超时消费】Nack失败", ex);
            }
        }
    }
}